﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows.Forms;

namespace PdfFromJson
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void txt_json_TextChanged(object sender, EventArgs e)
        {
            var pdfJsonModel = ReadFromString(txt_json.Text);
            ApplyDataToForm(pdfJsonModel);
            WritePdfToFile(pdfJsonModel);
        }

        private void btn_select_json_file_Click(object sender, EventArgs e)
        {
            var selectedFileName = GetFilename();
            var pdfJsonModel = ReadFromFile(selectedFileName);
            ApplyDataToForm(pdfJsonModel);
            WritePdfToFile(pdfJsonModel);
        }

        private void btn_open_pdf_file_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_file_name.Text))
                MessageBox.Show("No file is generated. Please generate a file first!");
            else
                Process.Start(txt_file_name.Text);
        }

        private PdfJsonModel ReadFromString(string json)
        {
            using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                return Deserialize(stream);
            }
        }

        private PdfJsonModel Deserialize(Stream stream)
        {
            try
            {
                var serializer = new DataContractJsonSerializer(typeof(PdfJsonModel));
                return serializer.ReadObject(stream) as PdfJsonModel;
            }
            catch (SerializationException)
            {
                MessageBox.Show("Incorect format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ResetFields();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ResetFields();
            }

            return null;
        }

        private static string GetFilename()
        {
            using (var dialog = new OpenFileDialog())
            {
                dialog.Filter = "All files (*.Json)|*.json";

                dialog.InitialDirectory = Environment.CurrentDirectory;
                dialog.Title = "Please select json file.";

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    return dialog.FileName;
                }
            }

            return null;
        }

        private PdfJsonModel ReadFromFile(string selectedFileName)
        {
            if (selectedFileName == null)
                return null;

            using (var fs = File.OpenRead(selectedFileName))
            {
                return Deserialize(fs);
            }
        }

        private void ApplyDataToForm(PdfJsonModel pdfJsonModel)
        {
            if (pdfJsonModel == null)
            {
                ResetFields();
                return;
            }

            txt_isin.Text = pdfJsonModel.ISIN;
            txt_company_name.Text = pdfJsonModel.CompanyName;
            txt_capitalIqId.Text = pdfJsonModel.CapitalIQID;
            txt_file_name.Text = pdfJsonModel.Filename;
            txt_report_type.Text = pdfJsonModel.ReportType;
            btn_open_pdf_file.Enabled = true;
        }

        private static void WritePdfToFile(PdfJsonModel pdfJsonModel)
        {
            if (pdfJsonModel == null)
                return;

            if (pdfJsonModel.Filename == null)
            {
                MessageBox.Show("FileName is empty.");
                return;
            }

            using (var stream = File.Create(pdfJsonModel.Filename))
            {
                var byteArray = Convert.FromBase64String(pdfJsonModel.File);
                stream.Write(byteArray, 0, byteArray.Length);
            }
        }

        private void ResetFields()
        {
            txt_isin.Text = "";
            txt_company_name.Text = "";
            txt_capitalIqId.Text = "";
            txt_file_name.Text = "";
            txt_report_type.Text = "";
            btn_open_pdf_file.Enabled = false;
        }
    }
}
